package com.starbugs.wehcat.aop;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CgLibProxy implements MethodInterceptor {
  private CalcDao calcDao;

  public CgLibProxy(CalcDao calcDao) {
    this.calcDao = calcDao;
  }

  public CalcDao createProxy(){
    // 创建cglib核心类对象
    Enhancer enhancer = new Enhancer();
    // 设置父类，因为cglib的实现，是基于继承实现的
    enhancer.setSuperclass(calcDao.getClass());
    // 设置回调
    enhancer.setCallback(this);
    // 创建代理对象
    CalcDao proxy  = (CalcDao) enhancer.create();
    return  proxy;
  }

  @Override
  public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy)
      throws Throwable {
    if("save".equals(method.getName())){
      System.out.println("enhancer");
    }
    return methodProxy.invokeSuper(proxy, args);
  }
}
